package com.junmeng.libadapter.base;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 支持多种场景（DataBinding,ViewBinding等）的通用适配器
 * <p>
 * 用法示例：
 * CommonRecyclerAdapter adapter = new CommonRecyclerAdapter(new CommonBindViewManager());
 * recyclerView.setAdapter(adapter);
 *
 * @param <T>  item类名
 * @param <VH> ViewHolder：已实现的有RecyclerViewHolder，DataBindingViewHolder，ViewBindingViewHolder
 * @param <BV> BaseBindView：已实现的有BaseCommonBindView，BaseDataBindingBindView，BaseViewBindingBindView
 */
public class CommonRecyclerAdapter<T, VH extends RecyclerView.ViewHolder, BV extends BaseBindView> extends BaseRecyclerAdapter<T, VH> {

    public IBindViewManager<T, VH, BV> mBindViewManager;

    public CommonRecyclerAdapter(IBindViewManager<T, VH, BV> bindViewManager) {
        this.mBindViewManager = bindViewManager;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return mBindViewManager.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        mBindViewManager.onBindViewHolder(holder, position, getItem(position), payloads);
    }

    @Override
    public void onViewRecycled(@NonNull VH holder) {
        int pos = holder.getAdapterPosition();
        if (pos == -1) {
            return;
        }
        T item = getItem(pos);
        if (item == null) {
            return;
        }
        mBindViewManager.onViewRecycled(holder, item);
    }

    /**
     * 注册BindView
     *
     * @param bindView
     */
    public void register(@NonNull BV bindView) {
        bindView.userData = getUserData();
        bindView.ownerAdapter = new WeakReference(this);
        mBindViewManager.register(bindView);
    }

    @Override
    public int getItemViewType(int position) {
        return mBindViewManager.getItemViewType(position, getItem(position));
    }
}
